﻿using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using More.Application;
using More.Application.Json;
using More.Engine;
using More.Engine.Model;
using More.Web.Designer.Models;
using Newtonsoft.Json.Linq;

namespace More.Web.Designer.Controllers
{
    public class WebApiTestController : BaseController
    {
        //
        // GET: /WebAPI/
        public ActionResult Index()
        {
            return View(new TestRuleBookModel()
            {
                RuleBook = Strategy.GetRuleBook(this.CurrentRuleBookId).Name,
                EffectiveDate = MissionControlDate,
                Json = "{\r\n     \r\n}\r\n"
            });
        }

        [HttpPost]
        public ActionResult Execute(TestRuleBookModel model)
        {
            var date = model.EffectiveDate.HasValue ? model.EffectiveDate.Value : DateTime.Now;
            var assemblyName = MoreApplicationFactory.GetAssemblyName(date);
            //var assemblyFileName = Path.Combine(AppDomain.CurrentDomain.SetupInformation.PrivateBinPath, assemblyName + ".dll");

            var compiler = MoreApplicationFactory.GetCompiler(date);

            var results = compiler.Build(
                                         new CompilerParameters()
                                         {
                                             GenerateInMemory = true,
                                             GenerateExecutable = false
                                         });
           
            if (results.Errors.HasErrors)
            {
                var lstErrors = new List<CompilerErrorModel>();
                foreach (CompilerError error in results.Errors)
                    lstErrors.Add(new CompilerErrorModel(error.ErrorText, error.Line, error.Column));
                return View("Errors", lstErrors);
            }

            var inputs = JsonHelper.FromJson(model.Json);
            var rulesEngine = new RulesEngine();
            
            var factory = rulesEngine.GetFactory(assemblyName,
                results.CompiledAssembly,
                MoreApplicationFactory.GetRatingEngineTableRepository(date)
                );
            if (factory == null)
            {
                return Content("Either the assembly was not found.  Or it was compiled incorrectly. Recompile and try again.");
            }
            var rb = factory.GetRuleBook(model.RuleBook);

            if (rb == null)
            {
                return Content("Rule book not found.");
            }

            var result = rb.Execute(inputs);
            if (result.Errors.Any())
            {
                var errors = result.Errors.Select(p=>new { message= p.Message, rb=p.Type}).ToArray();
                return Json(errors, JsonRequestBehavior.AllowGet);
            }
            //if (model.Items != null && model.Items.Length > 0 && model.Items.First() != "null")
            //{
            //    return model.Items.ToDictionary(item => item, result.Find);
            //}
            JObject obj = JObject.Parse(JsonHelper.GetJsonTrace(result.Results));
            return Content(obj.ToString());
            //return Content(JsonHelper.GetJsonTrace(result.Results));
        }
    }
}